package com.photovoltaic.auth.controller;

import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.entity.User;
import com.photovoltaic.auth.payload.request.LoginRequest;
import com.photovoltaic.auth.payload.request.SignupRequest;
import com.photovoltaic.auth.payload.response.JwtResponse;
import com.photovoltaic.auth.payload.response.MessageResponse;
import com.photovoltaic.auth.security.jwt.JwtUtils;
import com.photovoltaic.auth.security.services.UserDetailsImpl;
import com.photovoltaic.auth.service.OperationLogService;
import com.photovoltaic.auth.service.RoleService;
import com.photovoltaic.auth.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthenticationManager authenticationManager;
    private final UserService userService;
    private final RoleService roleService;
    private final PasswordEncoder encoder;
    private final JwtUtils jwtUtils;
    private final OperationLogService operationLogService;
    
    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);
        
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 获取用户角色
        List<String> roles = userDetails.getAuthorities().stream()
                .map(item -> item.getAuthority())
                .collect(Collectors.toList());
        
        // 获取用户所有权限（包括直接权限和通过角色获得的权限）
        List<String> permissions = userService.getUserPermissions(userDetails.getId())
                .stream()
                .map(permission -> permission.getPermissionKey())
                .collect(Collectors.toList());
        
        // 记录登录日志
        operationLogService.recordLog(
                userDetails.getId(),
                "LOGIN",
                "用户登录成功",
                request.getRemoteAddr(),
                1
        );
        
        return ResponseEntity.ok(new JwtResponse(
                jwt,
                userDetails.getId(),
                userDetails.getUsername(),
                userDetails.getEmail(),
                userDetails.getRealName(),
                userDetails.getMobile(),
                roles,
                permissions));
    }
    
    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        if (userService.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误: 用户名已被使用!"));
        }
        
        if (userService.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误: 邮箱已被使用!"));
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(signUpRequest.getUsername());
        user.setEmail(signUpRequest.getEmail());
        user.setPassword(encoder.encode(signUpRequest.getPassword()));
        user.setRealName(signUpRequest.getRealName());
        user.setMobile(signUpRequest.getMobile());
        user.setStatus(1); // 默认启用
        
        userService.save(user);
        
        // 分配角色
        if (signUpRequest.getRoles() != null && !signUpRequest.getRoles().isEmpty()) {
            signUpRequest.getRoles().forEach(roleName -> {
                Role role = roleService.findByRoleName(roleName);
                if (role != null) {
                    userService.assignRole(user.getId(), role.getId());
                }
            });
        } else {
            // 默认分配普通用户角色
            Role userRole = roleService.findByRoleName("ROLE_USER");
            if (userRole != null) {
                userService.assignRole(user.getId(), userRole.getId());
            }
        }
        
        return ResponseEntity.ok(new MessageResponse("用户注册成功!"));
    }
    
    @GetMapping("/user-info")
    public ResponseEntity<?> getUserInfo(@AuthenticationPrincipal UserDetailsImpl currentUser) {
        if (currentUser == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户未登录"));
        }
        
        User user = userService.findByUsername(currentUser.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户不存在"));
        }
        
        List<String> permissions = userService.getUserPermissions(user.getId())
                .stream()
                .map(permission -> permission.getPermissionKey())
                .collect(Collectors.toList());
        
        List<String> roles = userService.getUserRoles(user.getId())
                .stream()
                .map(role -> role.getName())
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(new JwtResponse(
                null, // 不返回token
                user.getId(),
                user.getUsername(),
                user.getEmail(),
                user.getRealName(),
                user.getMobile(),
                roles,
                permissions
        ));
    }
    
    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser(HttpServletRequest request, @AuthenticationPrincipal UserDetailsImpl currentUser) {
        // 即使没有认证用户也允许登出
        if (currentUser != null) {
            // 记录登出日志
            operationLogService.recordLog(
                    currentUser.getId(),
                    "LOGOUT",
                    "用户登出成功",
                    request.getRemoteAddr(),
                    1
            );
        } else {
            // 处理未认证用户的登出请求，可能是因为令牌已过期
            System.out.println("收到未认证用户的登出请求：" + request.getRemoteAddr());
        }
        
        return ResponseEntity.ok(new MessageResponse("登出成功"));
    }
} 